const { v4 } = require("uuid");
const OperationLogger = require("../core/operation-logger");
/**
 * 操作日志中间件
 * @param {*} options
 */
function operationLoggerMiddleware(options = {}) {
	const logger = new OperationLogger(options.pool);
	return async (ctx, next) => {
		const startTime = Date.now();
        const logData = {
            userId: '',
            tenantId: '',
            username: '',
            userType: 3,
            shopId: '',
            traceId: ctx.headers["trace_id"] || v4(),
            description: '',
			requestUri: ctx.url,
			requestMethod: ctx.method,
			ip: ctx.ip,
			userAgent: ctx.headers["user-agent"],
			module: ctx.path.split("/")[1] || "unknown",
			operation: ctx.method,
			status: 1 // 默认成功
		};
		try {
			// 获取用户信息
			if (ctx.state.user) {
				logData.userId = ctx.state.user ? ctx.state.user.uid : '';
				// logData.username = ctx.state.user.username;
				// logData.userType = ctx.state.user.type;
				// logData.shopId = ctx.state.user.shopId;
                logData.username = '';
				logData.userType = 3;
				logData.tenantId = ctx.state.tid || '';
				logData.shopId = ctx.state.sid || '';
			}

			// 记录请求数据
			logData.requestParams = ctx.request.params || {};
			logData.requestQuery = ctx.request.query || {};
			if (ctx.request.body && Object.keys(ctx.request.body).length > 0) {
				logData.requestBody = ctx.request.body;
			}
			await next();
            // 执行成功/失败
            if (ctx.response.status === 200) {
                logData.status = Number(ctx.response.body && ctx.response.body.code === 10000);
            } else {
                logData.status = 0;
            }
			// 记录响应数据
            logData.description = ctx.apiDescription;
            logData.requestParams = ctx.params || {};
			logData.responseData = ctx.body;
			logData.executionTime = Date.now() - startTime;
		} catch (err) {
			logData.status = 0;
			logData.errorCode = err.code || err.name;
			logData.errorMsg = err.message;
			logData.executionTime = Date.now() - startTime;
			throw err;
		} finally {
			// 异步记录日志
			process.nextTick(() => {
				logger.create(logData).catch(err => {
					console.error("日志记录失败:", err);
				});
			});
		}
	};
}

module.exports = operationLoggerMiddleware;
